#!/bin/sh

create_wine_dir ()
{
    # get params
    winedir=${1:?} ; shift			# only accept absolute path without trailing slash

    # exec wine command
    if [ ! -e "$winedir" ] ; then
        mkdir -p "$winedir"
    fi
    WINEPREFIX="$winedir" wineboot

    # change softlink to real directory in user directory
    userdir="$winedir/drive_c/users/$(id -un)"
    SAVEIFS=$IFS
    IFS=$'\n'
    for f in `find "$userdir" -print`
    do
        if [ ! -L "$f" ] ; then continue ; fi

        unlink $f
        mkdir $f
    done
}

create_link ()
{
    # get params
    srcdir=${1:?} ; shift			# only accept absolute path without trailing slash
    dstdir=${1:?} ; shift			# same as above
    dstdir_in="$dstdir/$(basename $srcdir)"
    
    # make dstdir in srcdir
    if [ ! -e "$dstdir_in" ] ; then
        mkdir -p "$dstdir_in"
    fi

    # do the job
    SAVEIFS=$IFS
    IFS=$'\n'
    for srcf in `find "$srcdir" -print`
    do
        # get inner filename
        f=${srcf:((${#srcdir}+1))}
        if [ "$f" == "" ] ; then continue ; fi

        # do the job
        if [[ -d "$srcf" && ! -L "$srcf" ]] ; then
            # create directory structure
            mkdir -p "$dstdir_in/$f"
        else
            # create softlink
            ln -s -t `dirname "$dstdir_in/$f"` $srcf
        fi
    done
    IFS=$SAVEIFS
}

# Variables
GAMEDIR=/opt/AngryBirds
DATADIR=~/.local/share/angry-birds

# Create wine directory
create_wine_dir "$DATADIR"

# Make links of "$GAMEDIR/*" to "$DATADIR"
if [ ! -e "$DATADIR/drive_c/Angry Birds" ] ; then
    create_link "$GAMEDIR/Angry Birds" "$DATADIR/drive_c"
fi

# Copy default user config file
cp -r "$GAMEDIR/default-config-user/*"   "$DATADIR/drive_c/users/$(id -un)/"

# run the game
cd "$DATADIR/drive_c/Angry Birds"
WINEPREFIX="$DATADIR" wine AngryBirds.exe

